﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XiaoYuStock.AppService.Storage;
using XiaoYuStockAnalysis.BusinessLogic.Business;
using XiaoYuStock.Core;
using XiaoYuStock.Core.Entities;
using XiaoYuStock.Core.Mails;
using XiaoYuStock.Model;
using XiaoYuStock.Model.Models;
using XiaoYuStock.Model.Request;

namespace XiaoYuStock.AppService
{
    public class DataMapping
    {

        private static ShareListDataBusiness shareBus = new ShareListDataBusiness();

        private static HistoryDataBusiness historyBus = new HistoryDataBusiness();




        /// <summary>
        /// 转换对象
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public  ShareList ConvertShareList(ShareData item, SharesType shareType,string subType)
        {
            var m = new ShareList();
            m.CirculateCapital = item.CirculateCapital;
            m.CreateDate = DateTime.Now;
            m.MarketDate = item.MarketDate;
            m.ShareCode = item.ShareCode;
            m.ShareName = item.ShareName;
            m.CategoryCode = item.CategoryCode;
         
            m.ShareType = (int)shareType;
            m.ShareSubType = subType;
            m.Status = (int)ShareState.Active;
            m.TotalCapital = item.TotalCapital;
            m.Url = item.Url;
            m.Flag = 0;
            return m;
        }

        /// <summary>
        /// 获取当天数据
        /// </summary>
        public static void GetSharesData()
        {
            int totalRecord = 0;
            ShareRequest request = new ShareRequest();
            request.PageSize = 100;
            request.ShareStatus = (int)ShareState.Active;
            request.PageIndex = 1;
            int pageCount = 0;
            LogHelper.InfoAsync("执行总数：" + totalRecord);
            do
            {
                var result = shareBus.GetList(request,out totalRecord);
                if (pageCount == 0)
                {
                    pageCount=(totalRecord + request.PageSize - 1) / request.PageSize;
                }
                foreach (var item in result)
                {
                    var sourceCode = Enum.GetName(typeof(SharesType), item.ShareType).ToLower() + item.ShareCode;

                    SynLoadCurrentDayData(sourceCode, item.ShareCode);
                   
                    System.Threading.Thread.Sleep(3000);

                }
                request.PageIndex++;

            }
            while (request.PageIndex<= pageCount);

        }
        private static void SynLoadCurrentDayData(string code, string shareCode)
        {
            try
            {
                LogHelper.InfoAsync("执行数据：" + code);
                var data = TransferDataHelper.LoadTransferData(code);
                HistoryData item = new HistoryData();
                item.CloseAmout = data.CurrentPrice; //3点后，当前价格就是收盘价
                item.CurrentDate = data.Date;
                item.MaxAmount = data.TodayTopPrice;
                item.MinAmount = data.TodayBomPrice;
                item.OpenAmount = data.TodayOpenPrice;
                item.ShareCode = data.SharesCode;
                item.TradeCount = data.TradeCount;
                item.TradeAmount = data.TradeAmount;
                item.TradeTime = Convert.ToDateTime(data.Date);
                item.DiffPrice = item.CloseAmout - data.YesterdayClosePrice;
                item.YesterdayCloseAmount = data.YesterdayClosePrice;
                if (data.YesterdayClosePrice > 0)
                {
                    item.TradeRate = Math.Round((decimal)(item.DiffPrice / data.YesterdayClosePrice) * 100, 2);
                }
                historyBus.SynData(item);
                SynLoadCurrentDayDataExtend(code, item);

            }
            catch (Exception ex)
            {
                //没有数据记录，更新当前数据
                LogHelper.ErrorAsync(string.Format("数据异常：{0},{1}", code, ex.Message));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="code"></param>
        /// <param name="entity"></param>
        public static void SynLoadCurrentDayDataExtend(string code, HistoryData entity)
        {
            try
            {
                LogHelper.InfoAsync("执行扩展数据：" + code);
                var data = HistoryDataServiceExtensions.LoadTransferData(code);
                if (data != null)
                {
                    entity.YesterdayCost = data.YesterdayCost;
                    entity.Support = data.Support;
                    entity.Pressure = data.Pressure;
                    entity.WeekTradeRate = data.WeekTradeRate;
                    entity.WeekDiffPrice = data.WeekDiffPrice;
                    entity.MonthTradeRate = data.MonthTradeRate;
                    entity.MonthDiffPrice = data.MonthDiffPrice;
                    entity.YearTradeRate = data.YearTradeRate;
                    entity.YearDiffPrice = data.YearDiffPrice;
                    entity.Ltg = data.Ltg;
                    entity.Mgjzc = data.Mgjzc;
                    entity.Income = data.Income;

                    historyBus.SynDataExtend(entity);
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorAsync(string.Format("数据扩展异常：{0},{1}", entity.ShareCode, ex.Message));
            }
        }

        /// <summary>
        /// 获取历史数据
        /// </summary>
        /// <param name="year"></param>
        /// <param name="season"></param>
        public static void GetSharesHistoryData(int year, int season)
        {
            int totalRecord = 0;
            ShareRequest request = new ShareRequest();
            request.PageSize = 100;
            request.ShareStatus = (int)ShareState.Active;
            request.Flag = 0;
            request.PageIndex = 1;
            do
            {
                var result = shareBus.GetList(request,out totalRecord);
                foreach (var item in result)
                {
                    SynUpdateHistoryData(item.ShareCode, year, season);
                    LogHelper.InfoAsync("执行获取股票历史：" + item.ShareCode);
                    item.Flag = 1;
                    shareBus.Update(item);
                    System.Threading.Thread.Sleep(1000 * 60);
                }
                request.PageIndex++;
            }
            while (totalRecord>0);

        }
        /// <summary>
        /// 获取历史数据
        /// </summary>
        /// <param name="shareCode"></param>
        /// <param name="Year"></param>
        /// <param name="Season"></param>
        public static void SynUpdateHistoryData(string shareCode, int year, int season)
        {
            HistoryDataService dataHeler = new HistoryDataService();
            dataHeler.SharesCode = shareCode;
            dataHeler.Year = year.ToString();
            dataHeler.Season = season;
            var d = dataHeler.GetDataRange();
            if (d != null)
            {
                foreach (var m in d)
                {
                    HistoryData item = new HistoryData();
                    item.CloseAmout = m.TodayClosePrice;
                    item.CurrentDate = m.Date;
                    item.MaxAmount = m.TodayTopPrice;
                    item.MinAmount = m.TodayBomPrice;
                    item.OpenAmount = m.TodayOpenPrice;
                    item.ShareCode = m.SharesCode;
                    item.TradeCount = m.TradeCount;
                    item.TradeAmount = m.TradeAmount;
                    item.TradeTime = Convert.ToDateTime(m.Date);
                    //item.DiffPrice = item.CloseAmout - m.YesterdayClosePrice;
                    //   item.TradeRate = Math.Round((decimal)(item.DiffPrice / m.YesterdayClosePrice) * 100, 2);
                    historyBus.SynData(item);

                }
            }
        }

        public void SendMail()
        {
            DateTime current = DateTime.Now;
            string title = current.ToString("yyyy-MM-dd") + "数据分析";
            string emails = string.Empty;
            if (System.Configuration.ConfigurationManager.AppSettings["emails"] != null)
                emails = System.Configuration.ConfigurationManager.AppSettings["emails"].ToString();
            var emailContent = StorageFactory.GetInstance().GetContent(current);
            if (!string.IsNullOrWhiteSpace(emailContent))
            {
                MyEmail.SendMail2(title, emailContent, string.Empty, emails.Split(';'));
            }

        }

        


    }
}
